﻿using System;
using System.Drawing;
using System.IO;
using System.Diagnostics;

namespace AudioCore.Common
{
    public class ImageCaching
    {
        private const string IMAGE_CACHING_FOLDER = "IMAGE_CACHING_FOLDER";
        private const string IMAGE_ROOT_FOLDER = "IMAGE_ROOT_FOLDER_FULLPATH";
        private const string EXTENSION = ".jpg";

        protected static TraceLog _ts = new TraceLog(Common.Constant.TraceSourceName.General, SourceLevels.All);
        private static string cachingFolder = string.Empty; // Caching folder
        private static string imageRootFolder = string.Empty;

        //http://210.245.80.142:81/imsg/img.aspx?w=100&h=100&c=0&u=http://dantri2.vcmedia.vn/ThumbImages/Uploaded/2010/08/14/hh21482010_327.jpg
        /// <summary>
        /// Get from other server and return image address on the local
        /// </summary>
        /// <param name="request">Request string</param>
        /// <param name="url">Image url on other server</param>
        /// <param name="crop">Crop image or not</param>
        /// <param name="w">Image width</param>
        /// <param name="h">Image height</param>
        /// <returns>Image address on local</returns>
        public static string GetImage(string request, string imageUrl, int crop, int w, int h)
        {
            bool cropImage = crop != 0 ? true : false;

            if (string.IsNullOrEmpty(cachingFolder)) //Read in first time only
            {
                // Create caching folder
                if (AppConfigUtils.GetString(IMAGE_CACHING_FOLDER, ref cachingFolder))
                {
                    if (!Directory.Exists(cachingFolder))
                    {
                        try
                        {
                            Directory.CreateDirectory(cachingFolder);
                        }
                        catch (Exception ex)
                        {
                            _ts.TraceError(ex.ToString());
                            return string.Empty;
                        }
                    }
                }
                else
                {
                    _ts.TraceError("Can not read IMAGE_CACHING_FOLDER key in configuration file.");
                    return string.Empty;
                }
            }

            // get image root folder
            if (string.IsNullOrEmpty(imageRootFolder))
            {
                if (!AppConfigUtils.GetString(IMAGE_ROOT_FOLDER, ref imageRootFolder))
                {
                    _ts.TraceError("Can not read ROOT_IMAGE_FOLDER key in configuration file.");
                    return string.Empty;
                }
            }

            string imagePath = request.Replace("/", string.Empty)
                .Replace("\\", string.Empty)
                .Replace(":", string.Empty)
                .Replace("*", string.Empty)
                .Replace("?", string.Empty)
                .Replace("<", string.Empty)
                .Replace(">", string.Empty)
                .Replace("|", string.Empty)
                .Replace(".", string.Empty);
            imagePath = cachingFolder + imagePath + EXTENSION;

            if (File.Exists(imagePath))
            {
                return imagePath;
            }

            System.Drawing.Image imgOriginal = null;
            //if (!string.IsNullOrEmpty(imageID))  //Get image from local
            //{
            //    int intImageID = 0;
            //    if (int.TryParse(imageID, out intImageID))
            //    {
            //        ImageBiz bizImage = new ImageBiz();
            //        string originalFileName = string.Empty;
            //        originalFileName = bizImage.GetOriginalImagePath(imageRootFolder, intImageID).Replace("\\\\","\\");
            //        if (File.Exists(originalFileName))
            //        {
            //            imgOriginal = System.Drawing.Image.FromFile(originalFileName);
            //        }
            //        else
            //        {
            //            return string.Empty;
            //        }
            //    }
            //    else
            //    {
            //        return string.Empty;
            //    }
            //}
            //else //Get image from internet
            {
                imgOriginal = ImageUtils.DownloadImage(imageUrl);
            }

            if (imgOriginal == null)
            {
                return string.Empty;
            }

            if (w == 0 || h == 0)
            {
                try
                {
                    imgOriginal.Save(imagePath);
                }
                catch (Exception ex)
                {
                    _ts.TraceError(ex.ToString());
                    return string.Empty;
                }
                imgOriginal.Dispose();
            }
            else
            {
                System.Drawing.Image imgResult = null;
                if (cropImage)
                {
                    imgResult = ImageUtils.ResizeImage(imgOriginal, new Size(w, h));
                }
                else
                {
                    imgResult = ImageUtils.Resize(imgOriginal, new Size(w, h));
                }
                try
                {
                    imgResult.Save(imagePath);
                }
                catch (Exception ex)
                {
                    _ts.TraceError(ex.ToString());
                    return string.Empty;
                }
                imgResult.Dispose();
            }

            return imagePath;
        }
    }
}
